package com.hmk.blogboot.dao;

import com.hmk.blogboot.po.Blog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/*blog数据访问层接口*/
public interface BlogRepository extends JpaRepository<Blog,Long>, JpaSpecificationExecutor<Blog> {

    @Query("select b from Blog b where b.recommend = true")
    List<Blog> findTop(Pageable pageable);

    /*根据blog的内容content或blog的title 模糊匹配查询*/
    @Query("select  b from Blog b  where b.title like ?1 or b.content  like ?1")
    Page<Blog>   findByQuery(String query,Pageable pageable);

    /*增加一个根据id 查询获取到blog 同时修改blog中浏览次数进行+1操作 jpa dao接口方法*/
    @Transactional
    @Modifying
    @Query("update Blog b set b.views= b.views+1  where b.id=?1")
    int updateViews(Long id);

    //按照年份获取列表 按照年份进行分组查询  查询到结果时间格式化工具进行格式化
    @Query("select function('date_format',b.updateTime,'%Y')  from Blog b  group by  function('date_format',b.updateTime,'%Y') order by function('date_format',b.updateTime,'%Y') desc ")
    List<String> findGroupYear();

    //根据年份查询blog列表
    @Query("select  b from Blog b  where function('date_format',b.updateTime,'%Y') = ?1 ")
    List<Blog> findByYear(String year);

}
